package com.software.frontend.searchmovie.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.software.frontend.R;
import com.software.frontend.searchmovie.utils.MyDBHelper;

import java.util.ArrayList;

public class SearchMovieRequestActivity extends AppCompatActivity {

    //搜索数据数据
    private ArrayList<String> historySearchData = new ArrayList<>();
    private ArrayList<String> hotSearchData = new ArrayList<>();
    //最外层的竖直线性布局(历史搜索和热门搜索)
    private LinearLayout ll_parent_history;
    private LinearLayout ll_parent_hot;
    private LinearLayout ll_remove_historyRecord;
    //Button控件
    private Button btn_search;
    private ImageButton iBtn_return;
    private SearchView sv_text;
    //存放历史搜索的数据库
    private SQLiteDatabase database;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_movie_request);
        //创建或打开数据库
        MyDBHelper myDBHelper = new MyDBHelper(this, "search.db", null, 1);
        database = myDBHelper.getWritableDatabase();
        initData();
        getViews();
        initAutoLL(ll_parent_history, historySearchData, 0);
        initAutoLL(ll_parent_hot, hotSearchData, 1);
        //设置点击事件监听器
        setListener();
    }

    private void setListener() {
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String str = sv_text.getQuery().toString();
                Log.e("abc", sv_text.getQuery().toString());
                if (str == null || str.equals("")){
                    return ;
                }
                String insertSQL = "insert into historysearch(record) values('" + str + "')";
                database.execSQL(insertSQL);
                initData();
                ll_parent_history.removeAllViews();
                initAutoLL(ll_parent_history, historySearchData, 0);
                //跳转到搜索结果页面
                Intent intent = new Intent(SearchMovieRequestActivity.this, SearchMovieResultActivity.class);
                intent.putExtra("searchStr", str);
                startActivity(intent);
            }
        });

        iBtn_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        ll_remove_historyRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String deleteSQL = "delete from historysearch";
                database.execSQL(deleteSQL);
                initData();
                ll_parent_history.removeAllViews();
                initAutoLL(ll_parent_history, historySearchData, 0);

            }
        });
    }

    //获取控件对象
    private void getViews() {
        ll_parent_history = (LinearLayout) findViewById(R.id.ll_parent_history);
        ll_parent_hot = (LinearLayout) findViewById(R.id.ll_parent_hot);
        btn_search = findViewById(R.id.search_movie_request_btn_search);
        iBtn_return = findViewById(R.id.search_movie_request_btn_return);
        sv_text = findViewById(R.id.search_movie_request_search_view);
        ll_remove_historyRecord = findViewById(R.id.ll_removeHistoryRecord);
    }

    //    初始化数据
    private void initData() {
        hotSearchData.add("我爱你");
        hotSearchData.add("不行");
        hotSearchData.add("你好");
        hotSearchData.add("回家");
        hotSearchData.add("为什么");
        hotSearchData.add("别紧张");
        hotSearchData.add("亲爱的");

        historySearchData.clear();
        Cursor result = database.rawQuery("select distinct RECORD from historysearch order by ID desc", null);
        //遍历游标，获取查询结果
        if(result.moveToFirst()){
            do {
//                int idIndex = result.getColumnIndex("ID");
                int recordIndex = result.getColumnIndex("RECORD");
//                int id = result.getInt(idIndex);
                String recode = result.getString(recordIndex);
                historySearchData.add(recode);
            }while (result.moveToNext());
        }

    }

    //绘制自动换行的线性布局
    private void initAutoLL(LinearLayout ll_parent, ArrayList<String> datas, int flag) {
        if (datas.isEmpty()) {
            return ;
        }
        //每一行的布局，初始化第一行布局
        LinearLayout rowLL = new LinearLayout(this);
        LinearLayout.LayoutParams rowLP =
                new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
        float rowMargin = dipToPx(10);
        rowLP.setMargins(0, (int) rowMargin, 0, 0);
        rowLL.setLayoutParams(rowLP);
        boolean isNewLayout = false;
        float maxWidth = getScreenWidth() - dipToPx(30);
        //剩下的宽度
        float elseWidth = maxWidth;
        LinearLayout.LayoutParams textViewLP =
                new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
        textViewLP.setMargins((int) dipToPx(8), 0, 0, 0);
        for (int i = 0; i < datas.size(); i++) {
            //若当前为新起的一行，先添加旧的那行
            //然后重新创建布局对象，设置参数，将isNewLayout判断重置为false
            if (isNewLayout) {
                ll_parent.addView(rowLL);
                rowLL = new LinearLayout(this);
                rowLL.setLayoutParams(rowLP);
                isNewLayout = false;
            }
            //计算是否需要换行
            TextView textView = (TextView) getLayoutInflater().inflate(R.layout.textview_search_movie_request, null);
            if (flag == 0) {
                textView.setBackgroundResource(R.drawable.search_movie_textview_history_shape);
            } else {
                textView.setBackgroundResource(R.drawable.search_movie_textview_hot_shape);
                textView.setTextColor(0xFFFFFFFF);
            }
            textView.setText(datas.get(i));
            textView.measure(0, 0);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String str = textView.getText().toString();
                    sv_text.setQuery(str,false);
                    btn_search.performClick();
                }
            });
            //若是一整行都放不下这个文本框，添加旧的那行，新起一行添加这个文本框
            if (maxWidth < textView.getMeasuredWidth()) {
                ll_parent.addView(rowLL);
                rowLL = new LinearLayout(this);
                rowLL.setLayoutParams(rowLP);
                rowLL.addView(textView);
                isNewLayout = true;
                continue;
            }
            //若是剩下的宽度小于文本框的宽度（放不下了）
            //添加旧的那行，新起一行，但是i要-1，因为当前的文本框还未添加
            if (elseWidth < textView.getMeasuredWidth() + 80) {
                isNewLayout = true;
                i--;
                //重置剩余宽度
                elseWidth = maxWidth;
                continue;
            } else {
                //剩余宽度减去文本框的宽度+间隔=新的剩余宽度
                elseWidth -= textView.getMeasuredWidth() + dipToPx(8);
                if (rowLL.getChildCount() == 0) {
                    rowLL.addView(textView);
                } else {
                    textView.setLayoutParams(textViewLP);
                    rowLL.addView(textView);
                }
            }
        }
        //添加最后一行，但要防止重复添加
        ll_parent.removeView(rowLL);
        ll_parent.addView(rowLL);
    }

    //dp转px
    private float dipToPx(int dipValue) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dipValue,
                this.getResources().getDisplayMetrics());
    }

    //获得评论宽度
    private float getScreenWidth() {
        return this.getResources().getDisplayMetrics().widthPixels;
    }


}